<script>
import starIcon from "../static/star.png";
import starFillIcon from "../static/starFill.png";
import request from "../utils/request";
import persistence from "../store/persistence";
import { showToast } from "../utils";
import store from "../store"
import { appActionType } from "../store/modules/app"

export default {
  name: "collection",
  data() {
    return {
      starIcon,
      starFillIcon,
      isCollection: false,
    };
  },
  props: {
    wordInfo: {
      type: Object,
      default: () => ({}),
    },
  },
  watch: {
    wordInfo: {
      handler(val) {
        this.isCollection = !!(val && val.existFavorite);
      },
      immediate: true,
    },
  },
	emits: ["collection"],
  methods: {
    //收藏
    async handleCollection() {
      await request({
        url: "userFavoriteWords/add",
        data: this.wordInfo,
        errorHandle: true,
      });
			if (store.getters[appActionType.getters.getFirstCollection]) {
				showToast.default("可在 我的 - 我的收藏 中查看");
				store.commit(appActionType.mutations.setFirstCollection, false);
			}
      this.isCollection = true;
			this.$emit("collection", true);
    },
    //取消收藏
    async handleCancelCollection() {
      await request({
        url: "userFavoriteWords/del",
        data: {
          ids: [this.wordInfo.enWord],
        },
        errorHandle: true,
      });
      this.isCollection = false;
			this.$emit("collection", false);
    },
  },
};
</script>

<template>
  <view class="components">
    <image
      :src="starFillIcon"
      class="icon"
      v-if="isCollection"
      @click="handleCancelCollection"
    />
    <image :src="starIcon" class="icon" @click="handleCollection" v-else />
  </view>
</template>

<style scoped lang="scss">
.components {
  .icon {
    width: 60rpx;
    height: 60rpx;
  }
}
</style>
